package cj.web.cc.controllers;

import java.io.File;
import java.text.ParseException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.Page;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.cc.dao.OnlineOrderDAO;
import cj.web.constants.ComposeSubjectTypeEnum;
import cj.web.constants.GameAreaEnum;
import cj.web.constants.GameTypeEnum;
import cj.web.constants.MemuEnum;
import cj.web.constants.OrderSourceEnum;
import cj.web.constants.PayStatusEnum;
import cj.web.constants.PayWayEnum;
import cj.web.constants.WXPayAttachEnum;
import cj.web.game.dao.GameDAO;
import cj.web.pay.alipay.util.PriceFormat;
import cj.web.pay.weixin.UnifiedOrder;

@Path("onlineOrder")
public class OnlineOrderController extends BaseController{
	@Autowired
	private OnlineOrderDAO onlineOrderDAO;
	@Autowired
	private GameDAO gameDao;
	
	/**
	 * 参赛详情
	 * @param model
	 * @param permitId
	 * @param request
	 * @return
	 */
	@Get("infor")
	public String infor(Model model, @Param("gameId") int gameId, HttpServletRequest request){
		List<Map> grades = onlineOrderDAO.asGradeEnum();
		model.add("Grade",grades);
//		List<Map> areas = onlineOrderDAO.asAreaEnum();
		model.add("Area", EnumSet.allOf(GameAreaEnum.class));
		model.add("phone", getCookieValueByName(request, "phone"));
		List<Map> games = onlineOrderDAO.getGameById(gameId);
		if(games != null && games.size() > 0 ){
			Map game = games.get(0);
			//返回对象
			Map gameObj = new HashMap();
			String price = PriceFormat.formatPrice(game.get("price"));
			String duration = game.get("duration").toString();
			String gameType = game.get("type").toString();
			String gameName = game.get("name").toString();
			String img = game.get("img").toString();
			
			gameObj.put("img", img);
			gameObj.put("price", price);
			gameObj.put("duration", duration);
			gameObj.put("gameType", gameType);
			gameObj.put("gameName", gameName);
			gameObj.put("gameId", gameId);
			model.add("gameObj", gameObj);
		}
		
		
		model.add("currentTopMemu", MemuEnum.memuhdbm);
		return "/views/onlineOrder/fillForm.vm";
	}
	
	/**
	 * 确认订单
	 * @param gameId		活动ID
	 * @param gameType		活动类型
	 * @param duration		活动时间范围
	 * @param permitId		参赛证号ID
	 * @param areaName		参赛区域名
	 * @param schoolName	参赛学校名
	 * @param address		参赛地址
	 * @param code			参赛证号
	 * @param price			参赛价格
	 * @param parentName	父母名称
	 * @param parentPhone	父母电话
	 * @param name			报名名称
	 * @param identityCard	身份证号
	 * @param school		学校
	 * @param grade			年级
	 * @param area			区域
	 * @param teacher		指导老师
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@Post("confirmInfor")
	public String confirmInfor(Model model,@Param("gameId")int gameId,@Param("gameType")int gameType, @Param("gameName")String gameName,
			@Param("duration")String duration, @Param("permitId")int permitId, @Param("areaName")String areaName,
			@Param("schoolName")String schoolName, @Param("address")String address, @Param("code")String code,
			@Param("returnCode")String returnCode, @Param("price")String price, @Param("parentName")String parentName,
			@Param("parentPhone")String parentPhone, @Param("name")String name,	@Param("identityCard")String identityCard,
			@Param("school")String school, @Param("grade")String grade,	@Param("area")String area, @Param("teacher")String teacher,
			@Param("img")String img, HttpServletRequest request) throws Exception{
		model.add("gameId", gameId);
		model.add("gameType", gameType);
		model.add("gameName", gameName);
		model.add("duration", duration);
		model.add("price", price);
		model.add("parentName", parentName);
		model.add("parentPhone", parentPhone);
		model.add("name", name);
		model.add("identityCard", identityCard);
		model.add("school", school);
		model.add("grade", grade);
		model.add("area", area);
		model.add("teacher", teacher);
		model.add("img", img);
		
		if(request.getHeader("user-agent").toLowerCase().indexOf("micromessenger") != -1){ //微信浏览器
			model.add("payWay", PayWayEnum.WX.getValue());
			model.add("source", OrderSourceEnum.WX.getValue());
			Map<String, String> config = getConfigSign(request);
			model.add("Config", config);
		}
		else{  //网站
			model.add("payWay", PayWayEnum.ZFB.getValue());
			model.add("source", OrderSourceEnum.WZ.getValue());
		}
		model.add("currentTopMemu", MemuEnum.memuhdbm);
		return "/views/onlineOrder/confirmForm.vm";
	}
	
	/**
	 * 检查活动订单填入信息
	 * @param gameId
	 * @param permitId
	 * @param parentName
	 * @param parentPhone
	 * @param name
	 * @param identityCard
	 * @param school
	 * @param grade
	 * @param payWay
	 * @param source
	 * @param area
	 * @param teacher
	 * @param inputCode
	 * @param request
	 * @return
	 * @throws Exception
//	 */
	@Post("checkOrder")
	public String checkOrder(@Param("gameId")int gameId, @Param("permitId")int permitId,
			@Param("identityCard")String identityCard,@Param("code")String inputCode,HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		String memberId = getCookieValueByName(request, "memberId");
		String phone = getCookieValueByName(request, "phone");
		//验证活动和帐号最大报名次数
		List<Map> games = onlineOrderDAO.getGameById(gameId);
		if(games != null && games.size() > 0){
			
			String endDate = games.get(0).get("endDate").toString();
			int flag = DateUtils.compareDateWithNow(DateUtils.parse(endDate));//与活动时间比较是否结束
			if(flag<0){
				//活动结束
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_6);
			}
			
			int maxApplyCount = Integer.parseInt(games.get(0).get("maxApplyCount").toString());//最大参赛人数
			
			List<Map> orderlis = onlineOrderDAO.getOrderByUserId(Integer.parseInt(memberId), gameId);
			if(maxApplyCount<=orderlis.size()){
				jo.put("maxApplyCount", maxApplyCount);
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_5);
				return "@" + jo.toString();
			}
		}
		
		//验证考生身份信息
		List<Map> appliedOrders = onlineOrderDAO.getOrderByIDCard(identityCard, gameId);
		if( appliedOrders != null && appliedOrders.size() > 0 ){                 //该身份证已报名
			Map appliedOrder = appliedOrders.get(0);
			int status = Integer.parseInt(appliedOrder.get("status").toString());
			if( status == PayStatusEnum.WFK.getValue() ){
				String createUser = appliedOrder.get("createUser").toString();
				if(createUser.equals(phone)){ //该身份证已报名,未付费,请前往我的个人中心>我的报名支付
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);   
					jo.put("returnCode", Constants.returnObj.returnCode.code_1);
					return "@" + jo.toString();
				}
				else{                         //该身份证已报名,未付费,请前往createUser的个人中心>我的报名支付
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);   
					jo.put("returnCode", Constants.returnObj.returnCode.code_8);
					return "@" + jo.toString();
				}
				
			}
			else if ( status == PayStatusEnum.YFK.getValue() ){
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase); //该身份证已付费,已报名,不要重复报名
				jo.put("returnCode", Constants.returnObj.returnCode.code_2);
				return "@" + jo.toString();
			}
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 去支付-生成订单
	 * @param gameId
	 * @param duration
	 * @param permitId
	 * @param areaName
	 * @param schoolName
	 * @param address
	 * @param code
	 * @param returnCode
	 * @param price
	 * @param parentName
	 * @param parentPhone
	 * @param name
	 * @param identityCard
	 * @param school
	 * @param grade
	 * @param payWay
	 * @param source
	 * @param area
	 * @param teacher
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@Post("createOrder")
	public String createOrder(@Param("gameId")int gameId, @Param("parentName")String parentName, @Param("parentPhone")String parentPhone, 
			@Param("name")String name, @Param("identityCard")String identityCard, @Param("school")String school, 
			@Param("grade")String grade, @Param("payWay")int payWay, @Param("source")int source, @Param("area")String area,
			@Param("teacher")String teacher, @Param("code")String inputCode, HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String price = "",
				duration = "",
				gameType = "";
		String memberId = getCookieValueByName(request, "memberId");
		String phone = getCookieValueByName(request, "phone");
		//验证活动和帐号最大报名次数
		List<Map> games = onlineOrderDAO.getGameById(gameId);
		if(games != null && games.size() > 0){
			
			String endDate = games.get(0).get("endDate").toString();
			int flag = DateUtils.compareDateWithNow(DateUtils.parse(endDate));//与活动时间比较是否结束
			if(flag<0){
				//活动结束
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_6);
			}
			
			int maxApplyCount = Integer.parseInt(games.get(0).get("maxApplyCount").toString());//最大参赛人数
			
			List<Map> orderlis = onlineOrderDAO.getOrderByUserId(Integer.parseInt(memberId), gameId);
			if(maxApplyCount<=orderlis.size()){
				jo.put("maxApplyCount", maxApplyCount);
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnCode", Constants.returnObj.returnCode.code_5);
				return "@" + jo.toString();
			}
			
			price = games.get(0).get("price").toString();
			duration = games.get(0).get("duration").toString();
			gameType = games.get(0).get("type").toString();
		}
		
		//验证考生身份信息
		List<Map> appliedOrders = onlineOrderDAO.getOrderByIDCard(identityCard, gameId);
		if( appliedOrders != null && appliedOrders.size() > 0 ){                 //该身份证已报名
			Map appliedOrder = appliedOrders.get(0);
			int status = Integer.parseInt(appliedOrder.get("status").toString());
			if( status == PayStatusEnum.WFK.getValue() ){
				String createUser = appliedOrder.get("createUser").toString();
				if(createUser.equals(phone)){ //该身份证已报名,未付费,请前往我的个人中心>我的报名支付
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);   
					jo.put("returnCode", Constants.returnObj.returnCode.code_1);
					return "@" + jo.toString();
				}
				else{                         //该身份证已报名,未付费,请前往createUser的个人中心>我的报名支付
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);   
					jo.put("returnCode", Constants.returnObj.returnCode.code_8);
					return "@" + jo.toString();
				}
				
			}
			else if ( status == PayStatusEnum.YFK.getValue() ){
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase); //该身份证已付费,已报名,不要重复报名
				jo.put("returnCode", Constants.returnObj.returnCode.code_2);
				return "@" + jo.toString();
			}
		}
		
		//验证参赛证号是否已使用
		String orderNo = "";
	
		orderNo = ReturnUUID.getOrderNo(ReturnUUID.getRandomNum());
		
		List<Map> subjectlis = onlineOrderDAO.getComposeSubjectByGameIdAndGradeName(gameId, grade);
		int subjectId = 0;
		if(subjectlis!=null && subjectlis.size()>0){
			subjectId=Integer.valueOf(subjectlis.get(0).get("id").toString());
		}
		int status = PayStatusEnum.WFK.getValue();
		//修改 2018/9/26 网络作文修改为不需要支付
		//----------
		if(GameTypeEnum.WLZZ.getValue().equals(gameType)){
			status = PayStatusEnum.YFK.getValue();
		}
		//----------
		int orderId = onlineOrderDAO.createOrder(orderNo, memberId, gameId, duration, price, parentName, parentPhone, 
				name, identityCard, school, grade, source, status, phone, 
				area, teacher,subjectId);
		jo.put("orderId", orderId);
		
		//支付
		if( payWay == PayWayEnum.ZFB.getValue() ){     //支付宝支付
			
		}
		else if( payWay == PayWayEnum.WX.getValue() ){ //微信支付
			//调用微信接口
			String tmpPrice = String.valueOf(Float.parseFloat(price) * 100);
			String total_fee = tmpPrice.substring(0, tmpPrice.indexOf("."));
			String spbill_create_ip = request.getRemoteAddr();
			String notify_url = request.getScheme() +"://" + request.getServerName() + "/wxNotify/result";
	        String openId = getCookieValueByName(request, "openId");
	        if(openId != null && openId.length() > 0){
	        	jo.put("hasOpenId", true);
	        	UnifiedOrder unifiedOrder = new UnifiedOrder();
	    		Map prepay = unifiedOrder.getPrepayId("确认订单-我的报名", orderNo, total_fee, spbill_create_ip, notify_url, openId ,WXPayAttachEnum.WL.getValue());
	    		jo.put("rtn", prepay);
	        }
	        else{
	        	jo.put("hasOpenId", false);
	        }
		}
		
		return "@" + jo.toString();
	}
	
	/**
	 * 报名列表
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@Get("myApplyPage")
	public String myApplyPage(Model model,HttpServletRequest request) throws Exception{
		if(request.getHeader("user-agent").toLowerCase().indexOf("micromessenger") != -1){ //微信浏览器
			model.add("payWay", PayWayEnum.WX.getValue());
			Map<String, String> config = getConfigSign(request);
			model.add("Config", config);
		}
		else{  //普通浏览器
			model.add("payWay", PayWayEnum.ZFB.getValue());
		}
		
		model.add("currentTopMemu", MemuEnum.memuhdbm);
		return "/views/onlineOrder/uc/wx/onlineOrderList.vm";
	}
	
	//---------------PC-----------------
	/**
	 * pc版我的报名列表
	 * @param model
	 * @return
	 */
	@Get("pcApply")
	public String pcApply(Model model, HttpServletRequest request) {
		
		String phone = getCookieValueByName(request, "phone");
		model.add("phone", phone);
		model.add("currentMemu", MemuEnum.wlzw);
		model.add("currentTopMemu", MemuEnum.memugrzx);
		return "/views/onlineOrder/uc/onlineOrderList.vm";
	}
	
	/**
	 * pc版我的报名列表分页
	 * @param start
	 * @param length
	 * @param request
	 * @return
	 * @throws ParseException 
	 */
	@Post("pcApplylis")
	public String pcApplylis(@Param("start") int start,@Param("length") int length, HttpServletRequest request) throws ParseException {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String memberId = getCookieValueByName(request, "memberId");
		
		List<Map> repsList = onlineOrderDAO.getOrderByUserId(Integer.parseInt(memberId),start*length,length);
		
		for(Map rep:repsList){
			int gameId = Integer.parseInt(rep.get("gameId").toString());
			List<Map> games = onlineOrderDAO.getGameById(gameId);
			if(games != null && games.size() > 0 ){
				Map game = games.get(0);
				String gameType = game.get("type").toString();
				String img = game.get("img").toString();
				String gameName = game.get("name").toString();
				
				String endDate= game.get("endDate").toString();
				rep.put("flagEndDate",returnflagEndDate(endDate));
				rep.put("img", img);
				rep.put("gameType", gameType);
				rep.put("gameName", gameName);
				rep.put("payAt", DateUtils.formatDateStr(rep.get("updateAt").toString(),DateUtils.DATE_FULL_STR));
				//获奖信息--------------------------------start
				//参赛证号
				String code = rep.get("code")==null?"":rep.get("code").toString();
				//是否开始考试（0.未考试 1.已考试）
				int isExam = rep.get("isExam")==null?0:Integer.parseInt(rep.get("isExam").toString());
				//是否阅卷（0.未批改 1.已批改）
				int isCheck = rep.get("isCheck")==null?0:Integer.parseInt(rep.get("isCheck").toString());
				Map levelRep = returnLevelInfor(code, gameId,isExam,isCheck,returnflagEndDate(endDate));
				boolean levelFlag=Boolean.valueOf(levelRep.get("levelFlag").toString());
				String level = levelRep.get("level").toString();
				rep.put("levelFlag", levelFlag);
				rep.put("level", level);
				
				//获奖信息--------------------------------end
			}
		}
		
		int totalCount = onlineOrderDAO.getOrderByUserIdSize(Integer.parseInt(memberId));
		
		//分页计算
		Page p= new Page<Map>(0, length, repsList, totalCount);
		jo.put("list", repsList);
		jo.put("repsize", p.getTotalPages());
		jo.put("totalCount", totalCount);
		return "@"+jo.toString();
	}
	
	/**
	 * 返回获奖信息及相关状态
	 * @param code
	 * @param gameId
	 * @return
	 */
	private Map returnLevelInfor(String code,int gameId,int isExam,int isCheck,boolean flagEndDate){
		Map rep = new HashMap();
		boolean levelFlag=false;
		if(!"".equals(code)){
			
			if(flagEndDate){
				//在活动范围内
				rep.put("levelFlag", levelFlag);
				rep.put("level", "比赛进行中");
				return rep;
			}else{
				//超出在活动范围内
				if(isCheck==1){
					//已批改
					//---------------------------------------成绩表查询结果
					List<Map> reportCard = onlineOrderDAO.queryByGameIdAndCode(gameId, code);
					if(reportCard!=null && reportCard.size()>0){
						//存在成绩
						String level = reportCard.get(0).get("level")==null?"":reportCard.get(0).get("level").toString();
						if(level!=null && !"".equals(level)){
							//非空
							rep.put("levelFlag", true);
							rep.put("level", level);
						}else{
							//空
							rep.put("levelFlag", levelFlag);
							rep.put("level", "暂无获奖信息");
						}
					}else{
						//不存在成绩
						rep.put("levelFlag", levelFlag);
						rep.put("level", "暂无获奖信息");
					}
					//---------------------------------------成绩表查询结果
				}else{
					//未批改
					rep.put("levelFlag", levelFlag);
					rep.put("level", "等待批改试卷");
					return rep;
				}
			}
			
		}else{
			//参赛证号为空
			rep.put("levelFlag", levelFlag);
			rep.put("level", "无");
		}
		
		return rep;
	}
	
	/**
	 * 判断是否时间结束
	 * @param endDate
	 * @return
	 */
	private boolean returnflagEndDate(String endDate){
		boolean flag = false;
		int flagendDate = DateUtils.compareDateWithNow(DateUtils.parse(endDate));
		if(flagendDate>=0){
			flag=true;
		}else{
			flag=false;
		}
		return flag;
	}
	
	/**
	 * 查看报名详情
	 * @param model
	 * @param orderId 活动订单id
	 * @return
	 * @throws Exception 
	 */
	@Get("dtPCFormPage")
	public String detailPCFormPage(Model model, @Param("orderId") int orderId, HttpServletRequest request) throws Exception{
		List<Map> gameOrder = onlineOrderDAO.getOrderById(orderId);
		boolean flagEndDate = false;
		if(gameOrder!=null && gameOrder.size()>0){
			
			int gameId = Integer.parseInt(gameOrder.get(0).get("gameId").toString());
			List<Map> games = onlineOrderDAO.getGameById(gameId);
			if(games != null && games.size() > 0 ){
				Map game = games.get(0);
				String gameType = game.get("type").toString();
				String img = game.get("img").toString();
				String gameName = game.get("name").toString();
				
				String endDate= game.get("endDate").toString();
				flagEndDate = returnflagEndDate(endDate);
				model.add("flagEndDate",flagEndDate);
				model.add("img", img);
				model.add("gameType", gameType);
				model.add("gameName", gameName);
				model.add("createAt", DateUtils.formatDateStr(gameOrder.get(0).get("createAt").toString(),DateUtils.DATE_FULL_STR));
				model.add("payAt", DateUtils.formatDateStr(gameOrder.get(0).get("updateAt").toString(),DateUtils.DATE_FULL_STR));
				model.add("obj", gameOrder.get(0));
				
			}
		}
		
		//获奖信息--------------------------------
		
		String code = gameOrder.get(0).get("code")==null?"":gameOrder.get(0).get("code").toString();
		//是否开始考试（0.未考试 1.已考试）
		int isExam = gameOrder.get(0).get("isExam")==null?0:Integer.parseInt(gameOrder.get(0).get("isExam").toString());
		//是否阅卷（0.未批改 1.已批改）
		int isCheck = gameOrder.get(0).get("isCheck")==null?0:Integer.parseInt(gameOrder.get(0).get("isCheck").toString());
		
		Map levelRep = returnLevelInfor(code, Integer.parseInt(gameOrder.get(0).get("gameId").toString()),
				isExam,isCheck,flagEndDate);
		boolean levelFlag=Boolean.valueOf(levelRep.get("levelFlag").toString());
		String level = levelRep.get("level").toString();
		model.add("levelFlag", levelFlag);
		model.add("level", level);
		
		//获奖信息--------------------------------
		
		String phone = getCookieValueByName(request, "phone");
		model.add("phone", phone);
		model.add("currentMemu", MemuEnum.wlzw);
		model.add("currentTopMemu", MemuEnum.memugrzx);
		return "/views/onlineOrder/uc/onlineOrderDetail.vm";
	}
	
	/**
	 * 查看报名详情
	 * @param model
	 * @param orderId 活动订单id
	 * @return
	 * @throws Exception 
	 */
	@Get("dtFormPage")
	public String detailFormPage(Model model, @Param("orderId") int orderId, HttpServletRequest request) throws Exception{
		List<Map> gameOrder = onlineOrderDAO.getOrderById(orderId);
		boolean flagEndDate = false;
		if(gameOrder!=null && gameOrder.size()>0){
			
			int gameId = Integer.parseInt(gameOrder.get(0).get("gameId").toString());
			List<Map> games = onlineOrderDAO.getGameById(gameId);
			if(games != null && games.size() > 0 ){
				Map game = games.get(0);
				String gameType = game.get("type").toString();
				String img = game.get("img").toString();
				String gameName = game.get("name").toString();
				model.add("img", img);
				model.add("gameType", gameType);
				model.add("gameName", gameName);
				//是否到期
				String endDate= game.get("endDate").toString();
				flagEndDate = returnflagEndDate(endDate);
				model.add("flagEndDate", flagEndDate);
				model.add("obj", gameOrder.get(0));
				
				if(request.getHeader("user-agent").toLowerCase().indexOf("micromessenger") != -1){ //微信浏览器
					model.add("payWay", PayWayEnum.WX.getValue());
					Map<String, String> config = getConfigSign(request);
					model.add("Config", config);
				}
				else{  //普通浏览器
					model.add("payWay", PayWayEnum.ZFB.getValue());
				}
			}
		}
		
		//获奖信息--------------------------------
		
		String code = gameOrder.get(0).get("code")==null?"":gameOrder.get(0).get("code").toString();
		//是否开始考试（0.未考试 1.已考试）
		int isExam = gameOrder.get(0).get("isExam")==null?0:Integer.parseInt(gameOrder.get(0).get("isExam").toString());
		//是否阅卷（0.未批改 1.已批改）
		int isCheck = gameOrder.get(0).get("isCheck")==null?0:Integer.parseInt(gameOrder.get(0).get("isCheck").toString());
				
		Map levelRep = returnLevelInfor(code, Integer.parseInt(gameOrder.get(0).get("gameId").toString()),
				isExam,isCheck,flagEndDate);
		boolean levelFlag=Boolean.valueOf(levelRep.get("levelFlag").toString());
		String level = levelRep.get("level").toString();
		model.add("levelFlag", levelFlag);
		model.add("level", level);

		//获奖信息--------------------------------
		
		model.add("currentTopMemu", MemuEnum.memuhdbm);
		return "/views/onlineOrder/detailForm.vm";
	}
	
	//----------我的报名

	/**
	 * 修改考生信息
	 * @param model
	 * @param orderId
	 * @return
	 */
	@Get("upFormPage")
	public String upFormPage(Model model, @Param("orderId") int orderId){
		List<Map> grades = onlineOrderDAO.asGradeEnum();
		model.add("Grade",grades);
		List<Map> areas = onlineOrderDAO.asAreaEnum();
		model.add("Area", EnumSet.allOf(GameAreaEnum.class));
		
		List<Map> gameOrder = onlineOrderDAO.getOrderById(orderId);
		if(gameOrder!=null && gameOrder.size()>0){
			int gameId = Integer.parseInt(gameOrder.get(0).get("gameId").toString());
			List<Map> games = onlineOrderDAO.getGameById(gameId);
			if(games != null && games.size() > 0 ){
				Map game = games.get(0);
				String price = PriceFormat.formatPrice(game.get("price"));
				String gameType = game.get("type").toString();
				String img = game.get("img").toString();
				model.add("img", img);
				model.add("price", price);
				model.add("gameType", gameType);
				model.add("obj", gameOrder.get(0));
				
				for(Map area : areas){
					String areaName = area.get("name").toString();
					if( gameOrder.get(0).get("area").toString().indexOf(areaName) >= 0){
						model.add("selArea", areaName);
						break;
					}
				}
				
				for(Map grade : grades){
					String gradeName = grade.get("name").toString();
					if( gameOrder.get(0).get("grade").toString().indexOf(gradeName) >= 0){
						model.add("selGrade", gradeName);
						break;
					}
				}
			}
		}
		model.add("currentTopMemu", MemuEnum.memuhdbm);
		return "/views/onlineOrder/updateForm.vm";
	}
	
	/**
	 * 修改考生信息
	 * @param model
	 * @param orderId
	 * @return
	 * @throws ParseException 
	 */
	@Get("upPCFormPage")
	public String upPCFormPage(Model model, @Param("orderId") int orderId, HttpServletRequest request) throws ParseException{
		List<Map> grades = onlineOrderDAO.asGradeEnum();
		model.add("Grade",grades);
		List<Map> areas = onlineOrderDAO.asAreaEnum();
		model.add("Area", EnumSet.allOf(GameAreaEnum.class));
		
		List<Map> gameOrder = onlineOrderDAO.getOrderById(orderId);
		if(gameOrder!=null && gameOrder.size()>0){
			int gameId = Integer.parseInt(gameOrder.get(0).get("gameId").toString());
			List<Map> games = onlineOrderDAO.getGameById(gameId);
			if(games != null && games.size() > 0 ){
				Map game = games.get(0);
				String price = PriceFormat.formatPrice(game.get("price"));
				String gameType = game.get("type").toString();
				String img = game.get("img").toString();
				String gameName = game.get("name").toString();
				model.add("img", img);
				model.add("price", price);
				model.add("gameType", gameType);
				model.add("gameName", gameName);
				model.add("createAt", DateUtils.formatDateStr(gameOrder.get(0).get("createAt").toString(),DateUtils.DATE_FULL_STR));
				model.add("obj", gameOrder.get(0));
				
				for(Map area : areas){
					String areaName = area.get("name").toString();
					if( gameOrder.get(0).get("area").toString().indexOf(areaName) >= 0){
						model.add("selArea", areaName);
						break;
					}
				}
				
				for(Map grade : grades){
					String gradeName = grade.get("name").toString();
					if( gameOrder.get(0).get("grade").toString().indexOf(gradeName) >= 0){
						model.add("selGrade", gradeName);
						break;
					}
				}
			}
		}
		
		String phone = getCookieValueByName(request, "phone");
		model.add("phone", phone);
		model.add("currentMemu", MemuEnum.wlzw);
		model.add("currentTopMemu", MemuEnum.memugrzx);
		return "/views/onlineOrder/uc/onlineOrderModifyUser.vm";
	}
	
	/**
	 * 修改报名信息
	 * @param orderId
	 * @param name
	 * @param identityCard
	 * @param areaId
	 * @param school
	 * @param gradeId
	 * @param teacher
	 * @param parentName
	 * @param parentPhone
	 * @return
	 * @throws Exception
	 */
	@Post("upForm")
	public String upForm(@Param("orderId")int orderId,@Param("name")String name, @Param("identityCard")String identityCard, 
			@Param("area")String area, @Param("school")String school,@Param("grade")String grade,
			@Param("teacher")String teacher,@Param("parentName")String parentName,@Param("parentPhone")String parentPhone,
			HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		String phone = getCookieValueByName(request, "phone");
		try {
			List<Map> rep = onlineOrderDAO.getOrderById(orderId);
			if(rep!=null && rep.size()>0){
				int status = Integer.parseInt(rep.get(0).get("status").toString());
				int gameId = Integer.parseInt(rep.get(0).get("gameId").toString());
				
				//身份证是不是已经使用=状态为已付款
				int count = onlineOrderDAO.checkOrderByIdentityCard(identityCard, gameId, orderId);
				if(count>0){
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
					jo.put("returnCode", Constants.returnObj.returnCode.code_1);
					return "@" + jo.toString();
				}
				
				if(PayStatusEnum.WFK.getValue()==status){
					onlineOrderDAO.updateOrder(orderId, name, identityCard, area, school, grade, teacher, parentName, parentPhone, phone);
				}else{
					jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
					jo.put("returnCode", Constants.returnObj.returnCode.code_3);
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Post("wxpay")
	public String wxpay(@Param("orderId")int orderId, HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String price = "",
				orderNo = "";
		List<Map> orders = onlineOrderDAO.getOrderById(orderId);
		if( orders != null && orders.size() > 0 ){ //验证订单是否存在
			Map order = orders.get(0);
			int status = Integer.parseInt(order.get("status").toString());
			if( status == PayStatusEnum.YFK.getValue() ){
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase); //是否已付款
				jo.put("returnCode", Constants.returnObj.returnCode.code_2);
				return "@" + jo.toString();
			}
			price = order.get("price").toString();
			orderNo = order.get("orderNo").toString();
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_1);
			return "@" + jo.toString();
		}
		
		//调用微信接口
		String tmpPrice = String.valueOf(Float.parseFloat(price) * 100);
		String total_fee = tmpPrice.substring(0, tmpPrice.indexOf("."));
		String spbill_create_ip = request.getRemoteAddr();
		String notify_url = request.getScheme() +"://" + request.getServerName() + "/wxNotify/result";
        String openId = getCookieValueByName(request, "openId");
        if(openId != null && openId.length() > 0){
        	jo.put("hasOpenId", true);
        	UnifiedOrder unifiedOrder = new UnifiedOrder();
    		Map prepay = unifiedOrder.getPrepayId("确认订单-我的报名", orderNo, total_fee, spbill_create_ip, notify_url, openId ,WXPayAttachEnum.WL.getValue());
    		jo.put("rtn", prepay);
        }
        else{
        	jo.put("hasOpenId", false);
        }
        
        return "@" + jo.toString();
	}
	
	@Post("alipay")
	public String alipay(@Param("orderId")int orderId, HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> orders = onlineOrderDAO.getOrderById(orderId);
		if( orders != null && orders.size() > 0 ){ //验证订单是否存在
			Map order = orders.get(0);
			int status = Integer.parseInt(order.get("status").toString());
			if( status == PayStatusEnum.YFK.getValue() ){
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase); //是否已付款
				jo.put("returnCode", Constants.returnObj.returnCode.code_2);
				return "@" + jo.toString();
			}
		}
		else{
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("returnCode", Constants.returnObj.returnCode.code_1);
			return "@" + jo.toString();
		}
		
		jo.put("orderId", orderId);
		return "@" + jo.toString();
	}
	
	//---------上传作品-----------
	/**
	 * 上传作品
	 * @param model
	 * @param permitId
	 * @param request
	 * @return
	 */
	@Get("upPage")
	public String upCompositionPage(Model model, @Param("orderId") int orderId, HttpServletRequest request){
		model.add("currentTopMemu", MemuEnum.memuhdbm);
		List<Map> composeOrderlis = onlineOrderDAO.getOrderById(orderId);
		if(composeOrderlis!=null && composeOrderlis.size()>0){
			//在线订单
			Map onlineOrder = composeOrderlis.get(0);
			//考试题号
			int subjectId = Integer.parseInt(onlineOrder.get("subjectId").toString());
			//考试题目
			Map composeSubject = onlineOrderDAO.getComposeSubjectById(subjectId).get(0);
			//考试题目类型
			int subjectType = Integer.parseInt(composeSubject.get("type").toString());
			//当前考试人员
			model.add("onlineOrder", onlineOrder);
			//相关题目
			model.add("composeSubject", composeSubject);
			
			//-----------------------------------------------------到期
			int gameId = Integer.parseInt(onlineOrder.get("gameId").toString());
			List<Map> games = onlineOrderDAO.getGameById(gameId);
			boolean flagEndDate = false;
			if(games != null && games.size() > 0){
				Map game = games.get(0);
				String endDate= game.get("endDate").toString();
				flagEndDate=returnflagEndDate(endDate);
			}
			
			//获奖信息--------------------------------
			
			String code = onlineOrder.get("code")==null?"":onlineOrder.get("code").toString();
			//是否开始考试（0.未考试 1.已考试）
			int isExam = onlineOrder.get("isExam")==null?0:Integer.parseInt(onlineOrder.get("isExam").toString());
			//是否阅卷（0.未批改 1.已批改）
			int isCheck = onlineOrder.get("isCheck")==null?0:Integer.parseInt(onlineOrder.get("isCheck").toString());
			
			Map levelRep = returnLevelInfor(code, Integer.parseInt(onlineOrder.get("gameId").toString()),
					isExam,isCheck,flagEndDate);
			boolean levelFlag=Boolean.valueOf(levelRep.get("levelFlag").toString());
			String level = levelRep.get("level").toString();
			model.add("levelFlag", levelFlag);
			model.add("level", level);
			
			//获奖信息--------------------------------
			
			if(flagEndDate){
				//活动时间范围内
				if(subjectType==Integer.parseInt(ComposeSubjectTypeEnum.ZW.getValue())){
					//题目类型作文
					return "/views/onlineOrder/upComposition.vm";
				}else if(subjectType==Integer.parseInt(ComposeSubjectTypeEnum.TP.getValue())){
					//题目类型图片
					return "/views/onlineOrder/upFile.vm";
				}
			}else{
				//活动结束
				if(subjectType==Integer.parseInt(ComposeSubjectTypeEnum.ZW.getValue())){
					//题目类型作文
					return "/views/onlineOrder/upCompositionDetail.vm";
				}else if(subjectType==Integer.parseInt(ComposeSubjectTypeEnum.TP.getValue())){
					//题目类型图片
					return "/views/onlineOrder/upFileDetail.vm";
				}
			}
		}
		return "/views/onlineOrder/upComposition.vm";
	}
	
	/**
	 * 提交作文页面
	 * @param model
	 * @param id
	 * @param composition
	 * @param request
	 * @return
	 */
	@Post("updateComposition")
	public String updateComposition(Model model, @Param("id") int id,@Param("composition") String composition,
			HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			String updateUser = getCookieValueByName(request, "phone");
			onlineOrderDAO.updateOrder(id, composition, updateUser);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 上传图片作品
	 * @param file
	 * @param request
	 * @return
	 */
	@Post("upload")
	public String upload(@Param("uploadimage") MultipartFile file,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
        if (!file.isEmpty()) {  
            try {  
                // 文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath");
            	// 判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	path = rep.get("allpath").toString();//所在的全路径
            	// 文件名
                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
                // 转存文件  
                file.transferTo(new File(path+"/"+fileName));  
                
                jo.put("filePath", rep.get("filepath")+"/"+fileName);
                
            } catch (Exception e) {  
                e.printStackTrace();  
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
		return "@"+jo.toString();
    }
}